package com.changgou.seckill.consumer;

import com.alibaba.fastjson.JSON;
import com.changgou.seckill.service.SeckillOrderService;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @author: hushengjin
 */

@Component
@RabbitListener(queues = "${mq.pay.queue.seckillorder}")
public class SeckillOrderPayMessageListener {

    @Autowired
    private SeckillOrderService seckillOrderService;

    @RabbitHandler
    public void consumerMessage(@Payload String msg) {
        Map<String, String> resultMap = JSON.parseObject(msg, Map.class);
        //返回状态码
        String return_code = resultMap.get("return_code");
        String result_code = resultMap.get("result_code");
        if (return_code.equalsIgnoreCase("success")) {
            //获取out_trade_no
            String outTradeNo = resultMap.get("out_trade_no");
            //获取附加消息
            Map<String, String> attachMap = JSON.parseObject(resultMap.get("attach"), Map.class);
            //支付成功
            if (result_code.equalsIgnoreCase("success")) {
                //修改订单状态
                seckillOrderService.updatePayStatus(outTradeNo, resultMap.get("transaction_id"),attachMap.get("username"));
            } else {
                //删除订单
                seckillOrderService.closeOrder(resultMap.get("username"));
            }
        }
    }

}
